package cn.ren.cloud.exception;

import cn.ren.cloud.enums.GlobelExceptionEnum;
import cn.ren.cloud.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 23508
 */
@Slf4j
@RestControllerAdvice
public class GlobalCustomExceptionHandler {

    /**
     * 全局异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e) {
        e.printStackTrace();
        log.error("发生异常啦~~~，异常信息为：" , e.getMessage());
        return JsonResult.error(GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_ERROR.getMessage(), GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_ERROR.getCode());
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JsonResult globalCustomExceptionHandler(GlobalCustomException e) {
        e.printStackTrace();
        log.error("发生异常啦~~~，异常信息为：{}, {}" , e.getMessage() , e.getCode());
        return JsonResult.error(e.getMessage(), e.getCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.error("发生异常啦~~~，异常信息为：{}, {}", e.getMessage(), GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_VALIDATION_ERROR.getCode());
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error-> stringBuilder.append(error.getDefaultMessage()).append(";") );
        return JsonResult.error(stringBuilder.toString(), GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_VALIDATION_ERROR.getCode());
    }
}
